<template>
  <a-modal
    destroyOnClose
    title="选择商品"
    v-model="visible"
    :afterClose="closeModel"
    :width="900"
    @ok="onOk"
    @cancel="onCancel()"
    :closable="false"
    :maskClosable="false"
  >
    <a-card>
      <a-row align="middle" style="margin-bottom: 10px">
        <a-space class="search-item">
          分类：
          <a-tree-select
            style="width: 200px"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择分类"
            allow-clear
            tree-default-expand-all
            @change="(e) => updateParam(e ? e : 0, 'cat_id')"
          >
            <a-icon slot="suffixIcon" type="search" />
            <a-tree-select-node v-for="item0 of catList" :key="item0.id" :value="item0.id" :title="item0.name">
              <a-tree-select-node
                v-if="item0.children.length > 0"
                v-for="item1 of item0.children"
                :key="item1.id"
                :value="item1.id"
                :title="item1.name"
              >
                <a-tree-select-node
                  v-if="item1.children.length > 0"
                  v-for="item2 of item1.children"
                  :key="item2.id"
                  :value="item2.id"
                  :title="item2.name"
                />
              </a-tree-select-node>
            </a-tree-select-node>
          </a-tree-select>
        </a-space>
        <a-space class="search-item"
          >商品名称：
          <a-input v-model="queryParam.name" placeholder="请填写搜索商品名称" />
        </a-space>
        <a-space class="search-item">
          <a-button @click="getList()" type="primary"> 搜索 </a-button>
        </a-space>
      </a-row>
      <a-row v-if="selectGoodsList.length > 0" type="flex" align="middle" class="img-list">
        <img
          class="selectImg"
          v-for="(goods1, index) of selectGoodsList"
          style="width: 30px; height: 30px; margin-right: 10px"
          :key="index"
          @click="delSelect(index)"
          :src="goods1.cover_pic"
          alt=""
        />
      </a-row>

      <a-table
        :columns="columns"
        :data-source="list"
        :loading="loading"
        :pagination="{
          total: this.totalCount,
          onChange: this.getList,
          onShowSizeChange: this.paginationSizeChange,
        }"
      >
        <template slot="name" slot-scope="name, goods">
          <!-- <a-row>
            <a-space>
              <img style="width: 40px; height: 40px" :src="goods.cover_pic" alt="" />
              ID{{ goods.id }}<span style="font-weight: bold">{{ name }}</span>
            </a-space>
          </a-row> -->
          <a-row>
            <a-space>
              <img style="width: 60px; height: 60px" :src="goods.cover_pic" alt="" />
              <span>
                <a-row>商品名称：{{ name }}</a-row>
                <a-row style="color: #d9534f">商品售价：{{ goods.price }}元</a-row>
                <a-row style="color: #666666">商品库存：{{ goods.goods_num }}</a-row>
              </span>
            </a-space>
          </a-row>
        </template>
        <a-space slot="action" slot-scope="text, goods">
          <a-button @click="selectGoods(goods)" size="small"> 选择 </a-button>
        </a-space>
      </a-table>
    </a-card>
  </a-modal>
</template>

<script>
import { list as catListApi } from '@/api/goods/cat'
import { list as Goods } from '@/api/goods/goods'

export default {
  data() {
    return {
      visible: false,

      columns: [
        {
          title: '商品信息',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '100px',
          scopedSlots: { customRender: 'action' },
        },
      ],

      catList: [],
      selectGoodsList: [],
      list: [],
      // loadData: parameter => {
      //   var newObj = {}
      //   Object.assign(newObj, parameter, this.queryParam)

      //   return Goods(newObj).then(res => {
      //     return res.data
      //   })
      // },

      queryParam: {
        name: '',
        cat_id: '',
        product_type: 0,
        // status: -1,
        // mch_id: 0
      },
    }
  },

  props: {
    countNum: {
      type: Number,
      default: 0,
    },
    checkList: {
      type: Array,
      default: () => []
    },

    selectedList: {
      type: Array,
      default() {
        return []
      },
    },
    // catId: {
    //   type: Number,
    //   default: 0
    // },

    // mchId: {
    //   type: Number,
    //   default: 0
    // }

    // addVerifyCard: {
    //   type: Boolean,
    //   default: false
    // }
  },

  watch: {
    visible: {
      immediate:true,
      handler(newVal, oldVal) {
        if(newVal && this.checkList.length) {
          this.selectGoodsList = this.checkList
        }
      }
    }
  },

  created() {
    this.getCatList()
    this.getList()
  },

  methods: {
    // 分页器页数修改回调
    paginationSizeChange(current, size) {
      this.pageSize = size
      this.getList(current)
    },

    getList(pageNo = 1) {
      this.loading = true
      let { queryParam, pageSize } = this
      Goods({
        ...queryParam,
        pageNo,
        pageSize,
      })
        .then((res) => {
          this.loading = false

          if (!res.code) {
            this.pageNo = pageNo
            this.list = res.data.data
            this.totalCount = res.data.totalCount
            return
          }

          this.$message.error(res.msg)
        })
        .catch(() => {
          this.loading = false
        })
    },

    // onEdit(id) {
    //   if (id > 0) {
    //     this.$router.push({ name: 'GoodsEdit', query: { id: id } })
    //   } else {
    //     this.$router.push({ name: 'GoodsEdit' })
    //   }
    // },

    /**
     * 获取分类
     */
    getCatList() {
      catListApi({ is_show: -1, mch_id: this.mchId }).then((res) => {
        this.catList = res.data.list
      })
    },

    selectGoods(goods) {
      let item = this.selectedList.find((el) => parseInt(el.goods_id) === parseInt(goods.id))

      if (item) return

      if (this.countNum > 0 && this.selectGoodsList.length >= this.countNum) {
        return false
      }

      let goodsInfo = {
        id: goods.id,
        virtual_sales: '',
        cover_pic: goods.cover_pic,
        name: goods.name,
        price: goods.price,
        goods_num: goods.goods_num,
        use_attr: goods.use_attr,
      }

      // if (goods.use_attr === '1') {
      if (!Array.isArray(goods.attr)) {
        goods.attr = JSON.parse(goods.attr)
      }
      let attr = goods.attr.map((el) => {
        el.seckill_num = ''
        el.seckill_price = ''
        return el
      })
      goodsInfo.attr = attr
      // } else {
      // goodsInfo.seckill_num = ''
      // goodsInfo.seckill_price = ''
      // }

      for (var i = 0; i < this.selectGoodsList.length; i++) {
        if (this.selectGoodsList[i].id === goods.id) {
          return false
        }
      }
      this.selectGoodsList.push(goodsInfo)
    },

    updateParam(value, type) {
      this.queryParam[type] = value
    },

    delSelect(index) {
      this.selectGoodsList.splice(index, 1)
    },

    onCancel() {
      this.visible = false
    },
    onOk() {
      this.visible = false
      this.$emit('onOk', this.selectGoodsList)
    },
    closeModel() {
      this.selectGoodsList = []
    },
  },
}
</script>
<style lang="less" scoped>
.permission-form {
  /deep/ .permission-group {
    margin-top: 0;
    margin-bottom: 0;
  }
}
.search-item {
  margin-left: 10px;
}
.selectImg:hover {
  opacity: 0.4;
}
.img-list {
  margin-bottom: 10px;
  background-color: #f6ffed;
  border: 1px solid #b7eb8f;
  padding: 6px;
  position: sticky;
  top: 0px;
  z-index: 999999999;
}
</style>
